﻿using ProtoBuf.Meta;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace huqiang.DataSet
{
    public class ProtoSerializer
    {
        static MemoryStream ms;
        public static T Deserialize<T>(byte[] dat)where T:class
        {
            if (ms == null)
                ms = new MemoryStream();
            else ms.Seek(0, SeekOrigin.Begin);
            ms.Write(dat, 0, dat.Length);
            ms.Seek(0, SeekOrigin.Begin);
            ms.SetLength(dat.Length);
            return ProtoBuf.Serializer.Deserialize<T>(ms);
        }
        public static byte[] Serialize<T>(T obj)
        {
            if (ms == null)
                ms = new MemoryStream();
            else
            { 
                ms.Seek(0, SeekOrigin.Begin);
                ms.SetLength(0);
            }
            ProtoBuf.Serializer.Serialize<T>(ms,obj);
            int len = (int) ms.Position;
            if (len == 0)
                return null;
            ms.Seek(0, SeekOrigin.Begin);
            byte[] buf = new byte[len];
            ms.Read(buf, 0, len);
            return buf;
        }
        public static void Compile()
        {
            var model = RuntimeTypeModel.Create();
            //model.AutoCompile = false;
            model.AllowParseableTypes = true;
            model.AutoAddMissingTypes = true;
            var ass = Assembly.GetAssembly(typeof(UnityLog));
            var types = ass.GetTypes();
            for (int i = 0; i < types.Length; i++)
            {
                if (types[i].Namespace == "huqiang.DataSet")
                {
                    var att = types[i].GetCustomAttribute(typeof(ProtoBuf.ProtoContractAttribute));
                    if (att != null)
                    {
                        model.Add(types[i], true);
                    }
                }
            }
            //model.Compile("ProtoData", "ProtoData.dll");
        }

        //public static void Compile(string folder)
        //{
        //    var model = RuntimeTypeModel.Create();
        //    var ass = Assembly.GetAssembly(typeof(UnityLog));
        //    var types = ass.GetTypes();
        //    for (int i = 0; i < types.Length; i++)
        //    {
        //        if (types[i].Namespace == "huqiang.DataSet")
        //        {
        //            var att = types[i].GetCustomAttribute(typeof(ProtoBuf.ProtoContractAttribute));
        //            if (att != null)
        //            {
        //                model.Add(types[i], true);
        //            }
        //        }
        //    }
        //    model.Compile("ProtoData", "ProtoData.dll");
        //    FileHelper.MoveFile("ProtoData.dll", folder + "/ProtoData.dll");
        //}
    }
}
